<?php
declare(strict_types = 1);

namespace leruge\command;

use think\console\Command;

class GenerateFile extends Command
{
    public function configure()
    {
        $this->setName('admin:generate')
            ->setDescription('创建文件');
    }

    public function handle()
    {
        // 创建admin应用
        $this->generatePhpFile(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'admin',
            app_path() . 'admin');
        // 创建静态资源
        // 创建种子
        $this->generatePhpFile(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'database',
            root_path() . 'database');
        // 创建模型
        $this->generatePhpFile(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'model',
            app_path() . 'model');
        // 创建验证器
        $this->generatePhpFile(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'validate',
            app_path() . 'validate');
        // 创建中间件
        $this->generatePhpFile(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'middleware',
            app_path() . 'middleware');
        // 创建api应用
        $this->generatePhpFile(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'api',
        app_path() . 'api');
    }

    private function generatePhpFile($sourcePath, $targetPath)
    {
        $sourcePath = $sourcePath . DIRECTORY_SEPARATOR;
        $targetPath = $targetPath . DIRECTORY_SEPARATOR;
        if (!file_exists($targetPath)) {
            mkdir($targetPath, 0777, true);
        }
        $handle = scandir($sourcePath);
        foreach ($handle as $file) {
            if (in_array($file, ['.', '..'])) {
                continue;
            }
            if (is_dir($sourcePath . $file)) {
                if (!file_exists($targetPath . $file)) {
                    mkdir($targetPath . $file, 0777, true);
                }
                $this->generatePhpFile($sourcePath . $file, $targetPath . $file);
            } else {
                $sourceFile = $sourcePath . $file;
                $targetFile = $targetPath . str_replace('.stub', '.php', $file);
                if (!file_exists($targetFile)) {
                    $content = file_get_contents($sourcePath . $file);
                    file_put_contents($targetFile, $content);
                }
            }
        }
    }
}